<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Http\Requests\Api\V1\OrderRequest;

use App\Models\Order;
use App\Models\UserAddress;

use App\Service\OrderService;
use App\Service\UserPointService;

use App\Http\Resources\V1\OrderResource;

use Spatie\QueryBuilder\QueryBuilder;
use Spatie\QueryBuilder\AllowedFilter;

use Carbon\Carbon;

class OrderController extends Controller
{
    public function store(OrderRequest $request, OrderService $service)
    {
        $address = UserAddress::find($request->address_id);

        $user = $request->user();

        $time = $request->order_time;

        $message = $request->input('message', '');

        $service->store($user, $address, $time, $message);

        return response(null, 201);
    }

    public function index(Request $request)
    {
        $orders = $request->user()->orders()
            ->orderStatus($request->input('status', 0))
            ->recent()
            ->paginate();

        return OrderResource::collection($orders);
    }

    public function complete(Order $order, Request $request, UserPointService $service)
    {
        $points = $service->addPoints($request->user());

        $order->update([
            'completed'     => true,
            'completed_at'  => Carbon::now(),
            'points'        => $points,
        ]);

        return response(null, 201);
    }

    public function close(Order $order)
    {
        $order->update([
            'closed'     => true,
            'closed_at'  => Carbon::now(),
        ]);

        return response(null, 201);
    }
}
